#include "raytracer.h"

#ifndef Q_MOC_RUN
#include <boost/random.hpp>
#include <boost/format.hpp>
#endif

RayTracer::RayTracer(Scene *scene, QWidget *parent) :
    QWidget(parent),
    _depth(4),
    _samples(64),
    _luminosity(4.0),
    _gamma(0.65)
{
    _scene = scene;
    _camera = _scene->camera();
    _renderer = new Renderer(_scene,width(),height(),_samples,_depth,this);
    connect(_renderer,SIGNAL(sampleComputed(int)),this,SLOT(sampleComputed(int)));
}

void RayTracer::render()
{
    _renderer->setWidth(width());
    _renderer->setHeight(height());
    _renderer->setDepth(depth());
    _renderer->setSamples(samples());
    _image = new QImage(width(),height(),QImage::Format_RGB32);
    _renderer->render();
}

void RayTracer::endScene()
{

}

void RayTracer::update()
{
    if(_renderer->isStarted())
    {
        _renderer->computeImage(*_image,_gamma,_luminosity);
        repaint();
    }
}

void RayTracer::paintEvent(QPaintEvent * e)
{
    if(_renderer->isStarted())
    {
        QPainter p(this);
        p.drawImage(rect(), *_image, _image->rect(), Qt::AutoColor);
    }
}

double RayTracer::luminosity() const
{
    return _luminosity;
}

void RayTracer::setLuminosity(double value)
{
    _luminosity = value;
}

double RayTracer::gamma() const
{
    return _gamma;
}

void RayTracer::setGamma(double value)
{
    _gamma = value;
}

Renderer *RayTracer::renderer()
{
    return _renderer;
}

void RayTracer::sampleComputed(int value)
{
    if(_renderer->isStarted())
    {
        _renderer->update();
        update();
    }
}

int RayTracer::depth() const
{
    return _depth;
}

void RayTracer::setDepth(int value)
{
    _depth = value;
}

void RayTracer::setSamples(int value)
{
    _samples = value;
}


int RayTracer::samples() const
{
    return _samples;
}
